<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Wechatoffiaccounts;
use App\Models\Minappslists;
use App\Models\Miniappsauthorization;
use App\Models\Minappslistsinfo;
use App\Models\Wechatoffiaccountsauthorization;
use App\Models\Minappstemplatelist;
use App\Models\Miniappsauditrestults;
use App\Models\Linkslistsminapps;
use App\Models\Usersauthority;
use App\Models\Users;
use App\Models\Mail;
use App\Models\Memberorders;
use App\Models\Minappimage;
use App\Models\Templatemini;
use App\Models\Keyorder;
use App\Models\Miniappsorder;
use App\Services\CommonService;
use App\Services\WechatService;
use App\Services\WechatopenService;
use App\Services\WechatwqopenService;
use App\Services\MiniappopenService;
use App\Services\MiniappService;
use App\Services\MiniappsetService;
use App\Services\WechatsService;
use App\Services\WechattmplmsgService;
use App\Services\WechaterrorService;
use App\Services\MiniappdataService;
use App\Services\OutputService;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Cache;
use EasyWeChat\Factory;
use App\Jobs\OfficialPush;
use Log,Artisan,Auth,Exception,Config;

class MiniappsController extends Controller
{
    public function miniIndex(Request $request)
    {
        $authority = Auth::user()->authority;
        $users_id = Auth::user()->id;

        // $member = Memberorders::getLastLinksOrders($users_id);
        // if (empty($member) || $member->end_time <= time()) return redirect("/admin/prices/products_lists")->with("status","error")->with("msg","请开通会员后使用本功能！");

        $minilists = Minappslists::getUsersMiniListsLists($authority,$users_id,$request->name,$request->appid);
        $status = [[],["class"=>"text-success","text"=>"可用"],["class"=>"","text"=>"试用预授权"],["class"=>"","text"=>"试用"],["class"=>"","text"=>"等待认证"],["class"=>"text-info","text"=>"认证成功"],["class"=>"text-warning","text"=>"小程序审核中"],["class"=>"text-danger","text"=>"小程序未通过"],["class"=>"text-primary","text"=>"待上架小程序"]];
        $status_code = ["0"=>"请先让企业管理员在手机微信完成认证!","100001"=>"已下发的模板消息法人并未确认且已超时（24小时），未进行身份证校验","100002"=>"已下发的模板消息法人并未确认且已超时（24小时），未进行人脸识别校验","100003"=>"已下发的模板消息法人并未确认且已超时（24小时）","101"=>"工商数据返回：“企业已注销”","102"=>"工商数据返回：“企业不存在或企业信息未更新”","103"=>"工商数据返回：“企业法定代表人姓名不一致”","104"=>"工商数据返回：“企业法定代表人身份证号码不一致”","105"=>"法定代表人身份证号码，工商数据未更新，请 5-15 个工作日之后尝试","1000"=>"工商数据返回：“企业信息或法定代表人信息不一致”","1001"=>"主体创建小程序数量达到上限","1002"=>"主体违规命中黑名单","1003"=>"管理员绑定账号数量达到上限","1004"=>"管理员违规命中黑名单","1005"=>"管理员手机绑定账号数量达到上限","1006"=>"管理员手机号违规命中黑名单","1007"=>"管理员身份证创建账号数量达到上限","1008"=>"管理员身份证违规命中黑名单","-1"=>"企业与法人姓名不一致，请删除后重新注册微信小程序!"];
        return view("admin.miniapp.register.miniapp_lists",["minilists"=>$minilists,"status"=>$status,"status_code"=>$status_code]);
    }

    public function miniappLists(Request $request)
    {
        $authority = Auth::user()->authority;
        $users_id = Auth::user()->id;

        // $member = Memberorders::getLastLinksOrders($users_id);
        // if (empty($member) || $member->end_time <= time()) return redirect("/admin/prices/products_lists")->with("status","error")->with("msg","请开通会员后使用本功能！");

        $minilists = Minappslists::getUsersMiniListsLists($authority,$users_id,$request->name,$request->appid);
        $status = [[],["class"=>"text-success","text"=>"可用"],["class"=>"","text"=>"试用预授权"],["class"=>"","text"=>"试用"],["class"=>"","text"=>"等待认证"],["class"=>"text-info","text"=>"认证成功"],["class"=>"text-warning","text"=>"小程序审核中"],["class"=>"text-danger","text"=>"小程序未通过"],["class"=>"text-primary","text"=>"待上架小程序"]];
        $status_code = ["0"=>"请先让企业管理员在手机微信完成认证!","100001"=>"已下发的模板消息法人并未确认且已超时（24小时），未进行身份证校验","100002"=>"已下发的模板消息法人并未确认且已超时（24小时），未进行人脸识别校验","100003"=>"已下发的模板消息法人并未确认且已超时（24小时）","101"=>"工商数据返回：“企业已注销”","102"=>"工商数据返回：“企业不存在或企业信息未更新”","103"=>"工商数据返回：“企业法定代表人姓名不一致”","104"=>"工商数据返回：“企业法定代表人身份证号码不一致”","105"=>"法定代表人身份证号码，工商数据未更新，请 5-15 个工作日之后尝试","1000"=>"工商数据返回：“企业信息或法定代表人信息不一致”","1001"=>"主体创建小程序数量达到上限","1002"=>"主体违规命中黑名单","1003"=>"管理员绑定账号数量达到上限","1004"=>"管理员违规命中黑名单","1005"=>"管理员手机绑定账号数量达到上限","1006"=>"管理员手机号违规命中黑名单","1007"=>"管理员身份证创建账号数量达到上限","1008"=>"管理员身份证违规命中黑名单","-1"=>"企业与法人姓名不一致，请删除后重新注册微信小程序!"];
        //判断小程序名称是否为空，如果为空去请求数据更新数据库
        foreach ($minilists as $key => $value) {
            if (empty($value->name)) {
                $miniAccessToken = MiniappopenService::miniappAccessToken($value->appid_third,$value->appid);
                if ($miniAccessToken["status"] == "error") continue;
                try {
                    $basicInfo = MiniappopenService::getAccountBasicInfo($miniAccessToken["access_token"]);
                    if (!empty($basicInfo['nickname'])) {
                        Minappslists::updateMiniappInfo($value->appid,["name"=>$basicInfo['nickname']]);
                        $minilists[$key]->name = $basicInfo['nickname'];
                    }
                } catch (Exception $e) {
                    
                }
                $basicInfo = MiniappopenService::getAccountBasicInfo($miniAccessToken["access_token"]);
            }
        }
        return view("admin.miniapp.register.miniapp_lists",["minilists"=>$minilists,"status"=>$status,"status_code"=>$status_code]);
    }

    public function officialList(Request $request)
    {
        $authority = Auth::user()->authority;
        $users_id = Auth::user()->id;

        $officialLists = Wechatoffiaccounts::getWechatOffiaccountsLists("","",$users_id);
        return view("admin.miniapp.register.official_list",["officialLists"=>$officialLists]);
    }

    public function officialDetial(Request $request,$appid)
    {
        $users_id = Auth::user()->id;
        $officialDetial = Wechatoffiaccounts::wechatOffiaccountsByAppid($appid);
        return view("admin.miniapp.register.official_detial",["officialDetial"=>$officialDetial]);
    }

    public function miniappRegister(Request $request)
    {
        $users_id = Auth::user()->id;
        $authority = Usersauthority::getUsersAuthority($users_id);
        return view("admin.miniapp.register.miniapp_register",["authority"=>$authority]);
    }

    public function miniappRegisterGzh(Request $request)
    {
        $users_id = Auth::user()->id;
        if (empty($request->app_id) && !isset($request->_token)) {
            $offiaccounts = Wechatoffiaccounts::getUsersWechatOffiaccounts($users_id);
            return view("admin.miniapp.register.miniapp_register_gzh",["offiaccounts"=>$offiaccounts]);
        } else {
            $appid = $request->app_id;
            if (empty($appid)) return back()->with("status","error")->with("msg","请选择微信公众号！");
            $offiAccount = Wechatoffiaccounts::wechatOffiaccountsByAppid($appid);
            if ($offiAccount->verify_type_info < 0) return back()->with("status","error")->with("msg","公众号未认证，无法快速创建小程序！");
            if ($offiAccount->users_id != $users_id) return back()->with("status","error")->with("msg","您无权执行本操作！");
            $openPlatform = Config::get("wechats.open_platform.beianbao");
            $component_appid = $openPlatform["app_id"];
            $url = "https://mp.weixin.qq.com/cgi-bin/fastregisterauth?appid=".$appid."&component_appid=".$component_appid."&copy_wx_verify=1&redirect_uri=https://bab.moreqifu.cn/admin/miniapps/miniapp_register_gzh_back/".$appid;
            return redirect($url);
        }
    }

    public function miniappRegisterGzhBack(Request $request,$offiaccount_appid)
    {
        try{
            // 获取公众号授权信息
            $offAuthorization = Wechatoffiaccountsauthorization::wechatOffiaccountsAuthorizationByAppid($offiaccount_appid);
            if (empty($offAuthorization)) return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg","公众号暂未授权,请先授权后再注册小程序！");
            // 公众号扫码授权的凭证
            $ticket = $request->ticket;
            try {
                // 第三方平台调用快速注册 API 完成注册
                $openConfig = config("wechats.open_platform.beianbao");
                $fastRegister = MiniappopenService::accountFastRegister($openConfig["app_id"],$offiaccount_appid,$offAuthorization->authorizer_refresh_token,$ticket,1);
                if ($fastRegister["errcode"] == 40001) {
                    $fastRegister = MiniappopenService::accountFastRegister($openConfig["app_id"],$offiaccount_appid,$offAuthorization->authorizer_refresh_token,$ticket,2);
                }
            } catch (Exception $e) {
                return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg","小程序注册失败；请检查公众号是否取消授权，如果是请重新授权后再注册小程序！");
            }
            try {
                if ($fastRegister["errcode"] != 0) {
                    $message = WechaterrorService::getErrorMessage($fastRegister["errcode"]);
                    return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg",$message);
                }
                $config = Config::get("wechats.open_platform.beianbao");
                $status = $fastRegister["is_wx_verify_succ"] ? 1 : 2;
                $users_id = Auth::user()->id;
                // 使用授权码获取授权信息
                $queryAuth = MiniappopenService::apiQueryAuth($config["app_id"],$fastRegister["authorization_code"]);
                // 保存授权信息
                Miniappsauthorization::insertOpenToken($config["app_id"],$fastRegister["appid"],$fastRegister["authorization_code"],time(),"",$status,time(),"",7200,$queryAuth["authorization_info"]["authorizer_refresh_token"],1);
                $openConfig = config("wechats.open_platform.beianbao");
                $authorizerInfo = MiniappopenService::apiGetAuthorizerInfo($openConfig["app_id"],$queryAuth["authorization_info"]["authorizer_appid"]);
                $authorizationInfo = $authorizerInfo["authorization_info"];
                $head_img = isset($authorizerInfo["authorizer_info"]["head_img"]) ? $authorizerInfo["authorizer_info"]["head_img"] : "";
                $minapps_lists_id = Minappslists::gzhRegisterAuth($users_id,$authorizerInfo["authorizer_info"]["nick_name"],$config["app_id"],$queryAuth["authorization_info"]["authorizer_appid"],$head_img,$authorizerInfo["authorizer_info"]["user_name"],$authorizerInfo["authorizer_info"]["qrcode_url"],5,2);
                Minappslistsinfo::fastRegister($minapps_lists_id,$authorizerInfo["authorizer_info"]["nick_name"],"","",$queryAuth["authorization_info"]["authorizer_appid"],$authorizerInfo["authorizer_info"]["user_name"]);
                MiniappsetService::miniappAdd($queryAuth["authorization_info"]["authorizer_appid"],["appid"=>$queryAuth["authorization_info"]["authorizer_appid"],"users_id"=>$users_id,"name"=>""]);
                return redirect("/admin/miniapps/miniapp_detial/".$queryAuth["authorization_info"]["authorizer_appid"])->with("status","success")->with("msg","小程序快速注册成功,请根据提示操作备案小程序!");
            } catch (Exception $e) {
                Log::info("fastRegisterGzhWeappBack-------");
                Log::info($e);
                Log::info("fastRegisterGzhWeappBack-------");
                return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg","授权注册小程序出现异常,请联系客服为您处理！");
            }
        } catch (Exception $e) {
            Log::info("fastRegisterGzhWeappBack-----");
            Log::info($request->all());
            Log::info($e);
            Log::info("fastRegisterGzhWeappBack-----");
        }
    }

    public function officialBind(Request $request)
    {
        // 获取公众号预授权码
        $preAuthcode = WechatsService::apiCreatePreauthcode();
        $config = Config::get("wechats.open_platform.beianbao");
        // 公众号授权链接
        $gzhurl = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=".$config["app_id"]."&pre_auth_code=".$preAuthcode["pre_auth_code"]."&redirect_uri=https://bab.moreqifu.cn/admin/miniapps/official_bind_back&auth_type=3";
        return redirect()->away($gzhurl);
    }

    public function officialBindBack(Request $request)
    {
        // 公众号授权返回
        // 使用授权码获取授权信息
        $apiQueryAuth = WechatsService::apiQueryAuth($request->auth_code);
        if (isset($apiQueryAuth["errcode"]) && $apiQueryAuth["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($apiQueryAuth["errcode"]);
            return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg",$message);
        }
        // 获取授权的权限集
        $funcInfos = $apiQueryAuth["authorization_info"]["func_info"];
        $funLists = [];
        foreach ($funcInfos as $funcInfo) {
            $funLists[] = $funcInfo["funcscope_category"]["id"];
        }
        if (!in_array(27, $funLists)) return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg","您未授权快速注册小程序权限,请重新授权!");
        if (!in_array(3, $funLists)) return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg","您未授权公众号账号信息服务权限,请重新授权!");
        // 保存授权码
        Wechatoffiaccountsauthorization::wechatOffiaccountsAuthorizationInsert($apiQueryAuth["authorization_info"]["authorizer_appid"],$apiQueryAuth["authorization_info"]["authorizer_access_token"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"]);

        // 获取授权方的帐号基本信息
        $apiGetAuthorizerInfo = WechatsService::apiGetAuthorizerInfo($apiQueryAuth["authorization_info"]["authorizer_appid"]);
        if (isset($apiGetAuthorizerInfo["authorizer_info"]["register_type"])) return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg","您授权的不是微信公众号,请授权微信公众号！");

        $original_id = $apiGetAuthorizerInfo["authorizer_info"]["user_name"];
        // 公众号头像
        $head_img = $apiGetAuthorizerInfo["authorizer_info"]["head_img"];
        $service_type_info = $apiGetAuthorizerInfo["authorizer_info"]["service_type_info"]["id"];
        $verify_type_info = $apiGetAuthorizerInfo["authorizer_info"]["verify_type_info"]["id"];
        // 判断是否存在数据
        $offiaccounts = Wechatoffiaccounts::wechatOffiaccountsByAppid($apiQueryAuth["authorization_info"]["authorizer_appid"]);
        if (empty($offiaccounts)) {
            // 添加数据
            Wechatoffiaccounts::wechatOffiaccountsAuthorizerInsert(Auth::user()->id,$apiGetAuthorizerInfo["authorizer_info"]["nick_name"],$apiGetAuthorizerInfo["authorization_info"]["authorizer_appid"],$original_id,$apiGetAuthorizerInfo["authorizer_info"]["principal_name"],$apiGetAuthorizerInfo["authorizer_info"]["signature"],$apiGetAuthorizerInfo["authorizer_info"]["qrcode_url"],$apiGetAuthorizerInfo["authorizer_info"]["alias"],$service_type_info,$verify_type_info,$head_img);
            $message = "公众号新增授权成功,您可以注册微信小程序!";
        } else {
            // 更新数据
            Wechatoffiaccounts::wechatOffiaccountsAuthorizerUpdate($offiaccounts->id,$apiGetAuthorizerInfo["authorizer_info"]["nick_name"],$apiGetAuthorizerInfo["authorization_info"]["authorizer_appid"],$original_id,$apiGetAuthorizerInfo["authorizer_info"]["principal_name"],$apiGetAuthorizerInfo["authorizer_info"]["signature"],$apiGetAuthorizerInfo["authorizer_info"]["qrcode_url"],$apiGetAuthorizerInfo["authorizer_info"]["alias"],$service_type_info,$verify_type_info,$head_img);
            if ($offiaccounts->users_id != Auth::user()->id) {
                $oldUsers = Users::getUsersById($offiaccounts->users_id);
                return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","error")->with("msg","本公众号已被账号：".$oldUsers->username."绑定,请勿重复绑定！");
            }
            $message = "公众号授权更新成功,您可以注册微信小程序!";
        }
        return redirect("/admin/miniapps/miniapp_register_gzh")->with("status","success")->with("msg",$message);
    }

    public function officialDelete(Request $request,$appid)
    {
        $users_id = Auth::user()->id;
        $officialDetial = Wechatoffiaccounts::wechatOffiaccountsByAppid($appid);
        if (empty($officialDetial) || $officialDetial->users_id != $users_id) return back()->with("status","error")->with("msg","微信公众号不存在!");
        Wechatoffiaccounts::wechatOffiacDisable($officialDetial->id,3);
        return redirect("/admin/miniapps/official_list")->with("status","success")->with("msg","公众号删除成功!");
    }

    public function miniappDelete(Request $request,$id)
    {
        $users_id = Auth::user()->id;
        $miniappDetial = Minappslists::getMiniListsListsById($id);
        if (empty($miniappDetial) || $miniappDetial->users_id != $users_id) return back()->with("status","error")->with("msg","微信小程序不存在!");
        Minappslists::minappsListsDelete($id,3);
        return redirect("/admin/miniapps/miniapp_lists")->with("status","success")->with("msg","微信小程序删除成功!");
    }

    public function miniappError(Request $request,$id)
    {
        $users_id = Auth::user()->id;
        $miniappDetial = Minappslists::getMiniListsListsById($id);
        if (empty($miniappDetial) || $miniappDetial->users_id != $users_id) return back()->with("status","error")->with("msg","微信小程序不存在!");
        $statusCodes = ["0"=>"请先让企业管理员在手机微信完成认证!","100001"=>"已下发的模板消息法人并未确认且已超时（24小时），未进行身份证校验","100002"=>"已下发的模板消息法人并未确认且已超时（24小时），未进行人脸识别校验","100003"=>"已下发的模板消息法人并未确认且已超时（24小时）","101"=>"工商数据返回：“企业已注销”","102"=>"工商数据返回：“企业不存在或企业信息未更新”","103"=>"工商数据返回：“企业法定代表人姓名不一致”","104"=>"工商数据返回：“企业法定代表人身份证号码不一致”","105"=>"法定代表人身份证号码，工商数据未更新，请 5-15 个工作日之后尝试","1000"=>"工商数据返回：“企业信息或法定代表人信息不一致”","1001"=>"主体创建小程序数量达到上限","1002"=>"主体违规命中黑名单","1003"=>"管理员绑定账号数量达到上限","1004"=>"管理员违规命中黑名单","1005"=>"管理员手机绑定账号数量达到上限","1006"=>"管理员手机号违规命中黑名单","1007"=>"管理员身份证创建账号数量达到上限","1008"=>"管理员身份证违规命中黑名单","-1"=>"企业与法人姓名不一致，请删除后重新注册微信小程序!"];
        try {
            $status = $statusCodes[$miniappDetial->status_code];
        } catch (Exception $e) {
            $status = "";
        }
        return view("admin.miniapp.register.miniapp_error",["miniappDetial"=>$miniappDetial,"status"=>$status]);
    }

    public function miniappRegisterCrop(Request $request)
    {
        $users_id = Auth::user()->id;
        $temMinis = Templatemini::userTemplateMini($users_id);
        $temMinis = $temMinis->whereIn('corp_type',[1,2]);
        return view("admin.miniapp.register.miniapp_register_corp",["temMinis"=>$temMinis]);
    }

    public function miniappRegisterCropSubmit(Request $request)
    {
        $users_id = Auth::user()->id;
        $openConfig = config("wechats.open_platform.beianbao");
        //根据id判断是快速还是直接填写的内容
        if (empty($request->id)) {
            $name = $request->name;
            $code_type = $request->code_type;
            $code = $request->code;
            $legal_persona_wechat = $request->legal_persona_wechat;
            $legal_persona_name = $request->legal_persona_name;
            if(empty($name)) return OutputService::error("请输入企业全称!");
            if(empty($code_type)) return OutputService::error("请选择证件类型!");
            if(empty($code)) return OutputService::error("请输入证件号码!");
            if(empty($legal_persona_wechat)) return OutputService::error("请输入法人微信号!");
            if(empty($legal_persona_name)) return OutputService::error("请输入法人姓名!");
            if($request->type == 1){
                // 添加模板
                Templatemini::templateMiniInsert($users_id,$name,$code_type,$code,$legal_persona_wechat,$legal_persona_name,$request->qualification_img);
            }
        } else {
            $temMini = Templatemini::templateMiniDetial($request->id);
            if (empty($temMini)) return OutputService::error("小程序注册企业模板不存在!");
            if ($temMini->users_id != $users_id) return OutputService::error("小程序注册企业模板不存在!");
            $name = $temMini->enterprise_name;
            $code_type = $temMini->code_type;
            $code = $temMini->code;
            $legal_persona_wechat = $temMini->legal_persona_wechat;
            $legal_persona_name = $temMini->legal_persona_name;
        }
        $registerStatus = MiniappopenService::fastRegisterWeapp($openConfig["app_id"],$name,$code,$code_type,$legal_persona_wechat,$legal_persona_name,"15658606443");
        if ($registerStatus["errcode"] != 0) {
            Log::info("miniappRegisterCropSubmit------");
            Log::info(json_encode($registerStatus));
            Log::info("miniappRegisterCropSubmit------");
            $message = WechaterrorService::getErrorMessage($registerStatus["errcode"]);
            return OutputService::error($message);
        }
        // 创建小程序列表
        $minapps_lists_id = Minappslists::fastRegisterWeapp($users_id,'',2,3);
        // 添加小程序
        Minappslistsinfo::fastRegisterWeapp($minapps_lists_id,'',$name,$code_type,$code,$legal_persona_wechat,$legal_persona_name);
        return OutputService::success("注册成功,请法人查看手机微信推送后完成认证!");
    }

    public function miniappRegisterPersonSubmit(Request $request)
    {
        $users_id = Auth::user()->id;
        $openConfig = config("wechats.open_platform.beianbao");
        //根据id判断是快速还是直接填写的内容
        if (empty($request->id)) {
            $idname = $request->idname;
            $wxuser = $request->wxuser;
            if(empty($idname)) return OutputService::error("请输入正确的个人用户名字!");
            if(empty($wxuser)) return OutputService::error("请输入正确的个人用户微信号!");
            if($request->type == 1){
                // 添加模板
                Templatemini::templateMiniInsert($users_id,'',1,'',$wxuser,$idname,$request->qualification_img);
            }
        } else {
            $temMini = Templatemini::templateMiniDetial($request->id);
            if (empty($temMini)) return OutputService::error("小程序注册个人模板不存在!");
            if ($temMini->users_id != $users_id) return OutputService::error("小程序注册个人模板不存在!");
            $idname = $temMini->enterprise_name;
            $wxuser = $temMini->legal_persona_wechat;
        }
        $registerStatus = MiniappopenService::fastRegisterPersonalWeapp($openConfig["app_id"],$idname,$wxuser,"15658606443");
        if ($registerStatus["errcode"] != 0) {
            Log::info("miniappRegisterCropSubmit------");
            Log::info(json_encode($registerStatus));
            Log::info("miniappRegisterCropSubmit------");
            $message = WechaterrorService::getErrorMessage($registerStatus["errcode"]);
            return OutputService::error($message);
        }else{
            Log::info("miniappRegisterCropSubmit------");
            Log::info(json_encode($registerStatus));
            Log::info("miniappRegisterCropSubmit------");
        }
        // 创建小程序列表
        $minapps_lists_id = Minappslists::fastRegisterWeapp($users_id,'',2,5);
        // 添加小程序
        Minappslistsinfo::fastRegisterPersonWeapp($minapps_lists_id,'',$idname,1,1,$wxuser,$idname,$registerStatus["taskid"],$registerStatus["authorize_url"],$registerStatus["status"]);
        return OutputService::success("提交成功，请用微信进行扫码验证!",$registerStatus["authorize_url"]);
    }

    public function miniappRegisterPerson(Request $request)
    {
        $users_id = Auth::user()->id;
        $temMinis = Templatemini::userTemplateMini($users_id);
        $temMinis = $temMinis->where('corp_type',3);
        return view("admin.miniapp.register.miniapp_register_person",["temMinis"=>$temMinis]);
    }

    public function componentRebindAdminBack(Request $request,$appid)
    {
        $taskid = $request->taskid;
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        $users_id = Auth::user()->id;
        if (empty($minapp)) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $rebindStatus = MiniappopenService::componentRebindAdmin($miniAccessToken["access_token"],$taskid);
        if ($rebindStatus["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($rebindStatus["errcode"]);
            return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","无效的 taskid！");
        }
        return redirect("/admin/miniapps/miniapp_detial/".$appid)->with("status","success")->with("msg","小程序管理员换绑成功!");
    }

    public function fastRegisterBetaweapp(Request $request)
    {
        $openid = $request->openid;
        return view("admin.miniapp.register.fast_register_beta_weapp",['openid'=>$openid]);
    }

    public function fastRegisterBetaweappSubmit(Request $request)
    {
        // $openid = Auth::user()->wechat_openid;
        $openid = $request->openid;
        $users_id = Auth::user()->id;
        if (empty($openid)) {
            return OutputService::error("请输入微信openid!");
            return back()->with("status","error")->with("msg","您的天天外链账号暂未绑定微信,请绑定后再操作!")->withInput();
        }
        if (empty($request->name)) {
            return OutputService::error("请输入小程序名称！");
            return back()->with("status","error")->with("msg","请输入小程序名称！")->withInput();
        }
        $openConfig = config("wechats.open_platform.beianbao");
        $weappInfo = MiniappopenService::fastRegisterBetaWeApp($openConfig["app_id"],$request->name,$openid);
        Log::info(json_encode($weappInfo));
        if ($weappInfo["errcode"] != 0) {
            $message = WechaterrorService::getErrorMessage($weappInfo["errcode"]);
            return OutputService::error($message);
            return back()->with("status","error")->with("msg",$message)->withInput();
        }
        $minapps_lists_id = Minappslists::fastRegister($users_id,$request->name,$weappInfo["unique_id"],2);
        Minappslistsinfo::fastRegister($minapps_lists_id,$request->name,$weappInfo["unique_id"],$weappInfo["authorize_url"],"","");
        return OutputService::success('success',$weappInfo["authorize_url"]);
        return redirect("/admin/miniapps/betaweapp_status/".$weappInfo["unique_id"]);
    }

    public function fastRegisterBetaWeappEvent(Request $request,$unique_id)
    {
        $minapps = Minappslists::getMiniAppByUniqueId($unique_id);
        if ($minapps->status == 2) return back()->with("status","error")->with("msg","您暂未扫码绑定管理员！");
        return redirect("/admin/miniapps/betaweapp_status/".$unique_id);
    }

    public function betaweappStatus(Request $request,$unique_id)
    {
        $minapps = Minappslists::getMiniListsListsByAppid($unique_id);
        $users_id = Auth::user()->id;
        if (empty($minapps)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapps->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        $minappslistsinfo = Minappslistsinfo::getMinappsListsInfo($minapps->id);
        $templates = Minappstemplatelist::getMinappsTemplateList();
        if (in_array($minapps->status, [5,6,7,8])) {
            $miniAccessToken = MiniappopenService::miniappAccessToken($minapps->appid);
            $auditStatus = MiniappopenService::getLatestAuditStatus($miniAccessToken["access_token"]);
            if(isset($auditStatus["status"]) && $auditStatus["status"] == 0){
                // 更新小程序为审核中
                if ($minapps->status == 6) Minappslists::minappsListsStatus($minapps->id,8);
                $minapps->status = 8;
            }
            if(isset($auditStatus["status"]) && $auditStatus["status"] == 1) {
                $minapps->status = 7;
            }
        } else {
            $auditStatus = [];
        }
        return view("admin.miniapp.register.betaweapp_status",["minapps"=>$minapps,"templates"=>$templates,"minappslistsinfo"=>$minappslistsinfo,"auditStatus"=>$auditStatus]);
    }

    public function weappStatus(Request $request,$appid)
    {
        $minapps = Minappslists::getMiniListsListsByAppid($appid);
        $users_id = Auth::user()->id;
        if (empty($minapps)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapps->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        $minappslistsinfo = Minappslistsinfo::getMinappsListsInfo($minapps->id);
        // 获取Token信息
        $templates = Minappstemplatelist::getMinappsTemplateList();
        if (in_array($minapps->status, [6,7,8])) {
            $miniAccessToken = MiniappopenService::miniappAccessToken($minapps->appid_third,$appid);
            $auditStatus = MiniappopenService::getLatestAuditStatus($miniAccessToken["access_token"]);

            if(isset($auditStatus["status"]) && $auditStatus["status"] == 0){
                // 更新小程序为审核中
                if ($minapps->status == 6) Minappslists::minappsListsStatus($minapps->id,8);
                $minapps->status = 8;
            }
            if (isset($auditStatus["status"]) && $auditStatus["status"] == 1) {
                $minapps->status = 7;
            }
        } else {
            $auditStatus = [];
        }
        return view("admin.miniapp.register.weapp_status",["minapps"=>$minapps,"templates"=>$templates,"minappslistsinfo"=>$minappslistsinfo,"auditStatus"=>$auditStatus]);
    }

    public function miniappAuditCancel(Request $request,$appid)
    {
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        $users_id = Auth::user()->id;
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        MiniappopenService::wxaUndocodeAudit($miniAccessToken["access_token"]);
        Minappslists::minappsListsStatusByAppid($appid,5);
        return redirect("/admin/miniapps/miniapp_detial/".$appid)->with("status","success")->with("msg","小程序审核撤回成功！");
    }

    public function verifyBetaWeappView(Request $request)
    {
        if(empty($request->unique_id)) return redirect("/app")->with("status","error")->with("msg","参数错误1！");
        $miniDetails = Minappslists::getMiniAppByUniqueId($request->unique_id);
        if(empty($miniDetails)) return redirect("/app")->with("status","error")->with("msg","参数错误2！");
        if($miniDetails->users_id != Auth::user()->id) return redirect("/app")->with("status","error")->with("msg","参数错误3！");
        return view("admin.miniapp.register.verify_beta_weapp",["miniDetails"=>$miniDetails]);
    }

    public function verifyBetaWeapp(Request $request,$unique_id)
    {
        if (empty($request->enterprise_name)) return OutputService::error("请输入企业名称，如果是“无主体名称个体工商户”则填“个体户+法人姓名”，例如“个体户张三”！");
        if (empty($request->code)) return OutputService::error("请输入企业代码！");
        if (empty($request->code_type)) return OutputService::error("请选择企业代码类型！");
        if (empty($request->legal_persona_wechat)) return OutputService::error("请输入法人微信号！");
        if (empty($request->legal_persona_name)) return OutputService::error("请输入法人姓名！");
        if (empty($request->legal_persona_idcard)) return OutputService::error("请输入法人身份证号！");
        $component_phone = "15658606443";
        $minapps = Minappslists::getMiniAppByUniqueId($unique_id);

        $users_id = Auth::user()->id;
        if (empty($minapps)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapps->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        $Authorization = Miniappsauthorization::getMiniappsAuthorizationSimple($minapps->appid);
        // 试用小程序快速认证
        $verifyStatus = MiniappopenService::verifyBetaWeApp($minapps->appid_third,$minapps->appid,$Authorization->authorizer_refresh_token,$request->enterprise_name,$request->code,$request->code_type,$request->legal_persona_wechat,$request->legal_persona_name,$request->legal_persona_idcard,$component_phone);
        if ($verifyStatus["errcode"] != 0) {
            Log::info($verifyStatus);
            $message = WechaterrorService::getErrorMessage($verifyStatus["errcode"]);
            return OutputService::error($message);
        }
        // 添加小程序认证信息
        Minappslistsinfo::updateMinappsListsInfo($minapps->id,$request->enterprise_name,$request->code,$request->code_type,$request->legal_persona_wechat,$request->legal_persona_name,$request->legal_persona_idcard,$component_phone);
        // 更新为认证状态
        Minappslists::minappsListsStatus($minapps->id,4);
        return OutputService::success('提交成功，请先完成法人扫脸认证，下一步是小程序管理员微信端确认转正！');
    }

    public function weappAudit(Request $request,$appid)
    {
        // 微信小程序发布以及升级
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        $users_id = Auth::user()->id;
        if (empty($minapp)) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","微信小程序不存在!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","微信小程序不存在!");
        if (!in_array($minapp->status,[1,8])) {
            if ($minapp->status == 6) return redirect("/admin/miniapps/miniapp_detial/".$appid)->with("status","warning")->with("msg","小程序正在审核中,请通过审核后再操作!");
            return redirect("/admin/miniapps/miniapp_detial/".$appid)->with("status","error")->with("msg","微信小程序未通过审核,无法提交去升级/发布小程序!");
        }

        // 获取Token信息
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);

        // 获取小程序基本信息
        $basicInfo = MiniappopenService::getAccountBasicInfo($miniAccessToken["access_token"]);

        // 判断小程序原来使用的模版,避免混乱
        if (empty($minapp->source_miniprogram_appid)) {
            $templates = Minappstemplatelist::getMinappsTemplateList();
        } else {
            $templates = Minappstemplatelist::getMinappsTemplateBySourceMiniprogramAppid($minapp->source_miniprogram_appid);
            if (!isset($templates[0])) {
                $templates = Minappstemplatelist::getMinappsTemplateList();
            }
        }
        $minappsListInfo = Minappslistsinfo::getMinappsListsInfo($minapp->id);
        return view("admin.miniapp.register.miniapp_audit",["minapps"=>$minapp,"templates"=>$templates,"minappsListInfo"=>$minappsListInfo]);
    }

    public function wxaCommit(Request $request,$unique_id)
    {
        // 提交小程序代码
        if (mb_strlen($unique_id) <= 18) {
            $minapps = Minappslists::getMiniListsListsByAppid($unique_id);
        } else {
            $minapps = Minappslists::getMiniAppByUniqueId($unique_id);
        }
        $users_id = Auth::user()->id;
        if (empty($minapps)) return OutputService::error("您无权操作本小程序!");
        if ($minapps->users_id != $users_id && Auth::user()->authority < 3) return OutputService::error("您无权操作本小程序!");

        $miniTemplete = Minappstemplatelist::getLastTemplateList();
        $template_id = $miniTemplete->template_id;
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapps->appid_third,$minapps->appid);
        $audit = MiniappopenService::wxaSubmitAudit($miniAccessToken["access_token"],[],"","","","","");
        if ($audit["errcode"] == 0) {
            // 设置模版业务域名
            $template = Minappstemplatelist::getMinappsTemplateByTemplateId($template_id);
            $requestdomain = empty($template->requestdomain) ? [] : explode(",",$template->requestdomain);
            $wsrequestdomain = empty($template->wsrequestdomain) ? [] : explode(",",$template->wsrequestdomain);
            $modifydomains = MiniappopenService::wxaModifyDomain($miniAccessToken["access_token"],"set",$requestdomain,$wsrequestdomain,[],[],[],[]);
            // 更新小程序状态
            Minappslists::updateMinappsInfo($minapps->id,["status"=>6]);
            // 更新版本信息
            Minappslistsinfo::updateMinappsLists($minapps->id,["version"=>$template->user_version,"template_id"=>$template->template_id]);
        } else {
            if ($audit["errcode"] == 85086) {
                // 上传小程序代码并生成体验版
                $commit = MiniappopenService::wxaCommit($miniAccessToken["access_token"],$template_id,'{"extEnable": true,"ext": {"name": "wechat","attr": {"host": "open.weixin.qq.com","users": ["user_1","user_2"]}}}','1.0','开发测试');
                // 更新上传小程序代码状态
                Minappslistsinfo::updateMinappsListsInfoWxaCommit($minapps->id,2);
                return OutputService::error("提交代码审核之前需提前上传代码，请重新提交!");
            } else {
                $message = WechaterrorService::getErrorMessage($audit["errcode"]);
            }
            return OutputService::error($message);
        }
        return OutputService::success("提交成功,等待腾讯官方审核！");
    }

    // 重新更新为未提交
    public function wxaReCommit(Request $request,$unique_id)
    {
        if (mb_strlen($unique_id) <= 18) {
            $minapps = Minappslists::getMiniListsListsByAppid($unique_id);
        } else {
            $minapps = Minappslists::getMiniAppByUniqueId($unique_id);
        }
        $users_id = Auth::user()->id;
        if (empty($minapps)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapps->users_id != $users_id && Auth::user()->authority < 3) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if (!in_array($minapps->status, [6,7])) return back()->with("status","error")->with("msg","小程序状态异常!");
        Minappslists::minappsListsStatus($minapps->id,5);
        if (mb_strlen($unique_id) <= 18) {
            return redirect("/admin/miniapps/weapp_status/".$unique_id);
        } else {
            return redirect("/admin/miniapps/betaweapp_status/".$unique_id);
        }
    }

    public function wxaRelease(Request $request,$appid)
    {
        // 发布微信小程序
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        $users_id = Auth::user()->id;
        if (empty($minapp)) return OutputService::error("微信小程序不存在!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return OutputService::error("微信小程序不存在!");
        if ($minapp->status != 8) return OutputService::error("小程序已发布,无需重复发布!");
        // 发布审核
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$minapp->appid);
        $releaseResult = MiniappopenService::wxaRelease($miniAccessToken["access_token"]);

        if ($releaseResult["errcode"] == 0) {
            // 添加到外链使用小程序列表
            $linksMiniapp = Linkslistsminapps::getLinksListsMinappsByAppid($minapp->appid);
            $minappListsInfo = Minappslistsinfo::getMinappsListsInfo($minapp->id);
            if (empty($linksMiniapp)) {
                $version = ($minapp->minappListsInfo <= 5) ? 1 : 2;
                Linkslistsminapps::linksListsMinappsThirdInsert($minapp->name,$minapp->appid,$minapp->users_id,$minapp->original_id,$version);
            }
            // 更新小程序列表和版本
            $version = isset($minappListsInfo->version) ? $minappListsInfo->version : "1.0.5";
            Minappslists::updateMinappsInfo($minapp->id,["status"=>1,"version"=>$version]);
            return OutputService::success("微信小程序发布成功,即将返回小程序详情!");
        } elseif ($releaseResult["errcode"] == 85052) {
            // 重复发布,提示无需重复发布
            Minappslists::minappsListsStatus($minapp->id,1);
        }
        $errormsg = WechaterrorService::getErrorMessage($releaseResult["errcode"]);
        return OutputService::error($errormsg);
    }

    public function miniappDetial(Request $request,$appid)
    {
        $miniapp = Minappslists::getMiniListsListsByAppid($appid);
        if (empty($miniapp)) return back()->with("status","error")->with("msg","您无权执行本操作！");
        if ($miniapp->users_id != Auth::user()->id && Auth::user()->authority != 3) return back()->with("status","error")->with("msg","您无权执行本操作！");
        $principal_types = ["个人","企业","媒体","政府","其他组织"];
        $account_types = ["","订阅号","服务号","小程序"];
        $status = [[],["class"=>"text-success","text"=>"可用"],["class"=>"","text"=>"试用预授权"],["class"=>"","text"=>"试用"],["class"=>"","text"=>"等待认证"],["class"=>"text-warning","text"=>"待提交审核"],["class"=>"text-warning","text"=>"小程序审核中"],["class"=>"text-danger","text"=>"小程序未通过"],["class"=>"text-primary","text"=>"待上架小程序"]];
        $miniAccessToken = MiniappopenService::miniappAccessToken($miniapp->appid_third,$miniapp->appid);
        if ($miniAccessToken["status"] == "error") return back()->with("status","error")->with("msg",$miniAccessToken["msg"]);
        try {
            $basicInfo = MiniappopenService::getAccountBasicInfo($miniAccessToken["access_token"]);
            if (empty($miniapp->head_img) && !empty($basicInfo["head_image_info"]["head_image_url"])) {
                Minappslists::updateMiniappHeadImg($appid,$basicInfo["head_image_info"]["head_image_url"]);
            }
        } catch (Exception $e) {
            $message = $e->getMessage();
            $message = json_decode(str_replace("Request access_token fail: ", "", $message));
            if (empty($message)) return back()->with("status","error")->with("msg","访问环境异常！");
            if ($message->errcode == 61003) return back()->with("status","error")->with("msg","小程序已被取消授权,请重新授权后访问！");
            if ($message->errcode == 61023) return back()->with("status","error")->with("msg","小程序授权错误,请重新授权后访问！");
            $basicInfo = [];
        }
        if(empty($basicInfo)) return back()->with("status","error")->with("msg","小程序状态异常,请联系客服为您处理！");
        if(empty($basicInfo["principal_name"])){
            //试用小程序去转正处理
            return redirect("/admin/miniapps/verify_beta_weapp/".$miniapp->unique_id);
        }
        $qualification_verify = $basicInfo["wx_verify_info"]["qualification_verify"];
        if ($qualification_verify) {
            $miniappsListsInfo = Minappslistsinfo::getMinappsListsInfo($miniapp->id);
            // access_token过期重新获取
            if ($basicInfo["errcode"] == 40001) {
                Redis::del("miniapp_access_token_".$appid);
                Redis::del("authorizer_access_token_".$miniapp->appid_third."_".$appid);
            }
            // if(!isset($basicInfo["account_type"])) return back()->with("status","error")->with("msg","小程序状态错误,请联系客服为您处理！");
            $template = Minappstemplatelist::getLastTemplateList();
            $icpEntranceInfo = MiniappopenService::getIcpEntranceInfo($miniapp->appid_third,$miniapp->appid);
            if ($icpEntranceInfo["errcode"] == 0) {
                $status = $icpEntranceInfo["info"]["status"];
                if ($status == 2 && $miniapp->beian != 3) {
                    Minappslists::updateBeianStatus($appid,3);
                } elseif ($status == 3 && $miniapp->beian != 4) {
                    Minappslists::updateBeianStatus($appid,4);
                } elseif ($status == 6 && $miniapp->beian != 5) {
                    Minappslists::updateBeianStatus($appid,5);
                } elseif ($status == 1024 && $miniapp->beian != 1) {
                    Minappslists::updateBeianStatus($appid,1);
                }
            }
            $icpStatus = ["2"=>"平台审核中","3"=>"平台审核驳回","4"=>"管局审核中","5"=>"管局审核驳回","6"=>"已备案","1024"=>"未备案","1025"=>"未备案&小程序信息未填","1026"=>"未备案&小程序类目未填","1027"=>"未备案&小程序信息未填&小程序类目未填","1028"=>"未备案&小程序未认证","1029"=>"未备案&小程序信息未填&小程序未认证","1030"=>"未备案&小程序类目未填&小程序未认证","1031"=>"未备案&小程序信息未填&小程序类目未填&小程序未认证"];
            if ($icpEntranceInfo["errcode"] != 0) {
                $message = WechaterrorService::getErrorMessage($icpEntranceInfo["errcode"]);
                return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg",$message);
            }
            $entranceInfo = $icpEntranceInfo["info"];

            $openPlatform = Config::get("wechats.open_platform.beianbao");
            $component_appid = $openPlatform["app_id"];
            return view("admin.miniapp.register.miniapp_detial",["entranceInfo"=>$entranceInfo,"miniapp"=>$miniapp,"basicInfo"=>$basicInfo,"principal_types"=>$principal_types,"account_types"=>$account_types,"status"=>$status,"icpStatus"=>$icpStatus,"minappsListsInfo"=>$miniappsListsInfo,"template"=>$template,"component_appid"=>$component_appid,"qualification_verify"=>$qualification_verify]);
        } else {
            return view("admin.miniapp.register.miniapp_detial",["basicInfo"=>$basicInfo,"qualification_verify"=>$qualification_verify,"miniapp"=>$miniapp]);
        }
    }

    public function minappPublish(Request $request,$appid)
    {
        $miniapp = Minappslists::getMiniListsListsByAppid($appid);
        if (empty($miniapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        $users_id = Auth::user()->id;
        if (empty($miniapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($miniapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");

        $miniAccessToken = MiniappopenService::miniappAccessToken($miniapp->appid_third,$miniapp->appid);
        if ($miniAccessToken["status"] == "error") return back()->with("status","error")->with("msg",$miniAccessToken["msg"]);
        $basicInfo = MiniappopenService::getAccountBasicInfo($miniAccessToken["access_token"]);
        if ($basicInfo["errcode"] != 0) {
            $errormsg = WechaterrorService::getErrorMessage($basicInfo["errcode"]);
            if ($basicInfo["errcode"] == 40001) {
                Redis::del("miniapp_access_token_".$appid);
            }
            return redirect("/admin/miniapps/miniapp_detial/".$appid)->with("status","error")->with("msg",$errormsg);
        }
        $miniappsListsInfo = Minappslistsinfo::getMinappsListsInfo($miniapp->id);
        $categories = MiniappopenService::getAllCategories($miniapp->appid_third,$miniapp->appid,"");
        $categories = json_encode($categories["categories_list"]["categories"]);
        $miniappTemplete = Minappstemplatelist::getLastTemplateList();
        return view("admin.miniapp.register.minapp_publish",["miniapp"=>$miniapp,"basicInfo"=>$basicInfo,"minappsListsInfo"=>$miniappsListsInfo,"miniappTemplete"=>$miniappTemplete,"categories"=>$categories]);
    }

    public function minappPublisSubmit(Request $request)
    {
        if (empty($request->appid)) return OutputService::error("参数错误!");
        if (empty($request->nickname)) return OutputService::error("请输入小程序名称!");
        if (empty($request->signature)) return OutputService::error("请输入小程序简介!");
        if (empty($request->media_id) && $request->head_image_url == "http://mmbiz.qpic.cn/mmbiz/a5icZrUmbV8p5jb6RZ8aYfjfS2AVle8URwBt8QIu6XbGewB9wiaWYWkPwq4R7pfdsFibuLkic16UcxDSNYtB8HnC1Q/0") return OutputService::error("请上传小程序LOGO!");
        $minapp = Minappslists::getMiniListsListsByAppid($request->appid);
        if (empty($minapp)) return OutputService::error("您无权操作本小程序!");
        $users_id = Auth::user()->id;
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return OutputService::error("您无权操作本小程序!");

        // if ($minapp->pay_status == 1) {
        //     $users = Users::getUsersDetial($users_id);
        //     if ($users->score < 100) return OutputService::error("账户积分不足,请充值后重新操作!");
        //     Users::decrementUsersScode($users_id,100);
        //     Minappslists::updateMinappListPayStatus($minapp->id,2);
        //     Keyorder::keyOrderCreate($users_id,100,$request->appid,1);
        // }

        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$minapp->appid);
        if ($miniAccessToken["status"] == "error") return back()->with("status","error")->with("msg",$miniAccessToken["msg"]);
        // 获取小程序基本信息
        $basicInfo = MiniappopenService::getAccountBasicInfo($miniAccessToken["access_token"]);
        if ($basicInfo["account_type"] != 3) return OutputService::error("您授权的是公众号非微信小程序，不支持上架小程序！");
        
        if ($basicInfo['nickname'] != $request->nickname) {
            // 微信认证名称检测
            $checkNickname = MiniappopenService::checkWxVerifyNickname($miniAccessToken["access_token"],$request->nickname);
            if ($checkNickname["errcode"] != 0) {
                $errormsg = WechaterrorService::getErrorMessage($checkNickname["errcode"]);
                if ($checkNickname["errcode"] == 91009) {
                    if (empty($request->naming_other_stuff)) return OutputService::error($errormsg,[],$checkNickname["errcode"]);
                } else {
                    return OutputService::error($errormsg,[],$checkNickname["errcode"]);
                }
            }
            if (!empty($checkNickname["wording"]) && empty($request->naming_other_stuff)) return OutputService::error($checkNickname["wording"],[],1007);
            $nickname = MiniappopenService::setNickname($miniAccessToken["access_token"],$request->nickname,$request->license,$request->naming_other_stuff);
            if ($nickname["errcode"] != 0) {
                $errormsg = WechaterrorService::getErrorMessage($nickname["errcode"]);
                return OutputService::error($errormsg);
            }
            //如果设置成功，则更新小程序名称
            Minappslists::updateMiniappInfo($minapp->appid,["name"=>$request->nickname]);
        }
        if ($basicInfo['signature_info']['signature'] != $request->signature){
            $signature = MiniappopenService::modifySignature($miniAccessToken["access_token"],$request->signature);
            if ($signature["errcode"] != 0) {
                $errormsg = WechaterrorService::getErrorMessage($signature["errcode"]);
                return OutputService::error($errormsg);
            }
        }
        if (!empty($request->media_id)){
            $mediaInfo = MiniappopenService::mediaUpload($minapp->appid_third,$minapp->appid,$request->media_id);
            $media_id = isset($mediaInfo["media_id"]) ? $mediaInfo["media_id"] : "";
            $modifyHead = MiniappopenService::modifyHeadImage($miniAccessToken["access_token"],$media_id);
            if ($modifyHead["errcode"] != 0) {
                $errormsg = WechaterrorService::getErrorMessage($modifyHead["errcode"]);
                return OutputService::error($errormsg);
            }
        }

        // 获取小程序配置详情
        $minappsListsInfo = Minappslistsinfo::getMinappsListsInfo($minapp->id);
        if (empty($minappsListsInfo)) {
            Minappslistsinfo::fastRegisterWeapp($minapp->id,$basicInfo["nickname"],$basicInfo["principal_name"],1,$basicInfo["credential"],"","");;
            $wxa_commit = 1;
            $category = 1;
        } else {
            $wxa_commit = $minappsListsInfo->wxa_commit;
            $category = $minappsListsInfo->category;
        }

        if ($category == 1) {
            // API添加微信小程序类型
            MiniappopenService::addCategory($miniAccessToken["access_token"],$request->categorie,$request->categorie_chlid);
            $category = 2;
        }
        if ($wxa_commit == 1) {
            // 上传小程序代码并生成体验版
            $template = Minappstemplatelist::getLastTemplateList();
            $wxaCommit = MiniappopenService::wxaCommit($miniAccessToken["access_token"],$template->template_id,'{"extEnable": true,"ext": {"name": "wechat","attr": {"host": "open.weixin.qq.com","users": ["user_1","user_2"]}}}','1.0','开发测试');
            $wxa_commit = 2;
        }

        // 修改小程序审核状态
        Minappslists::updateMinappsInfo($minapp->id,["name"=>$request->nickname]);
        // 修改小程序信息
        Minappslistsinfo::updateMinappsLists($request->appid,["name"=>$request->name,"signature"=>$request->signature,"category"=>$category,"wxa_commit"=>$wxa_commit,"release_method"=>$request->release_method]);
        return OutputService::success("小程序提交审核成功,请等待微信审核!");
    }

    public function wxaModifyDomain(Request $request,$appid)
    {
        $minapp = Minappslists::getMiniListsListsByAppid($appid);

        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        $users_id = Auth::user()->id;
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");

        // 获取Token信息
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $modifydomains = MiniappopenService::wxaModifyDomain($miniAccessToken["access_token"],"get",[],[],[],[],[],[]);
        $domains = ["requestdomain"=>"request 合法域名","wsrequestdomain"=>"socket 合法域名","uploaddomain"=>"uploadFile 合法域名","downloaddomain"=>"downloadFile 合法域名","udpdomain"=>"udp 合法域名","tcpdomain"=>"tcp 合法域名"];
        return view("admin.miniapp.register.miniapp_domain_modify",["appid"=>$appid,"modifydomains"=>$modifydomains,"domains"=>$domains]);
    }

    public function wxaModifyDomainSubmit(Request $request,$appid)
    {
        $minapp = Minappslists::getMiniListsListsByAppid($appid);

        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        $users_id = Auth::user()->id;
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");

        $requestdomain = empty($request->requestdomain) ? [] : explode(",",$request->requestdomain);
        $wsrequestdomain = empty($request->wsrequestdomain) ? [] : explode(",",$request->wsrequestdomain);
        $uploaddomain = empty($request->uploaddomain) ? [] : explode(",",$request->uploaddomain);
        $downloaddomain = empty($request->downloaddomain) ? [] : explode(",",$request->downloaddomain);
        $udpdomain = empty($request->udpdomain) ? [] : explode(",",$request->udpdomain);
        $tcpdomain = empty($request->tcpdomain) ? [] : explode(",",$request->tcpdomain);
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $modifydomains = MiniappopenService::wxaModifyDomain($miniAccessToken["access_token"],"set",$requestdomain,$wsrequestdomain,$uploaddomain,$downloaddomain,$udpdomain,$tcpdomain);

        if ($modifydomains["errcode"] != 0) {
            $errormsg = WechaterrorService::getErrorMessage($modifydomains["errcode"]);
            return back()->with("status","error")->with("msg",$errormsg);
        }

        return redirect("/admin/miniapps/wxa_modify_domain/".$appid)->with("status","success")->with("msg","服务器域名配置保存成功!");
    }

    public function wxaWebviewDomain(Request $request,$appid)
    {
        $minapp = Minappslists::getMiniListsListsByAppid($appid);

        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        $users_id = Auth::user()->id;
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");

        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $webviewdomains = MiniappopenService::setWebviewDomain($miniAccessToken["access_token"],"get",[]);
        return view("admin.miniapp.register.miniapp_domain_webview",["webviewdomains"=>$webviewdomains,"appid"=>$appid]);
    }

    public function wxaWebviewDomainSubmit(Request $request,$appid)
    {
        $minapp = Minappslists::getMiniListsListsByAppid($appid);

        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        $users_id = Auth::user()->id;
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");

        $webviewdomain = empty($request->webviewdomain) ? [] : explode(",",$request->webviewdomain);
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $setWebviewDomain = MiniappopenService::setWebviewDomain($miniAccessToken["access_token"],"set",$webviewdomain);
        if ($setWebviewDomain["errcode"] == 89019) return back()->with("status","error")->with("msg","业务域名无更改，无需重复设置!");
        if ($setWebviewDomain["errcode"] == 89020) return back()->with("status","error")->with("msg","尚未设置小程序业务域名，请先在第三方平台中设置小程序业务域名后在调用本接口!");
        if ($setWebviewDomain["errcode"] == 89021) return back()->with("status","error")->with("msg","请求保存的域名不是第三方平台中已设置的小程序业务域名或子域名!");
        if ($setWebviewDomain["errcode"] == 89029) return back()->with("status","error")->with("msg","业务域名数量超过限制，最多可以添加100个业务域名!");
        if ($setWebviewDomain["errcode"] == 89231) return back()->with("status","error")->with("msg","个人小程序不支持调用 setwebviewdomain 接口!");
        return redirect("/admin/miniapps/wxa_webview_domain/".$appid)->with("status","success")->with("msg","业务域名设置成功!");
    }

    public function changeWxaSearchStatus(Request $request,$appid)
    {
        $users_id = Auth::user()->id;
        $minapp = Minappslists::getMiniListsListsByAppid($appid);

        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $searchStatus = MiniappopenService::getWxaSearchStatus($miniAccessToken["access_token"]);
        if (!isset($searchStatus["status"])) {
            $message = WechaterrorService::getErrorMessage($searchStatus["errcode"]);
            return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg",$message);
        }
        return view("admin.miniapp.register.change_wxa_search_status",["searchStatus"=>$searchStatus,"minapp"=>$minapp]);
    }

    public function changeWxaSearchStatusSubmit(Request $request,$appid)
    {
        $users_id = Auth::user()->id;
        $minapp = Minappslists::getMiniListsListsByAppid($appid);

        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $changeStatus = MiniappopenService::changeWxaSearchStatus($miniAccessToken["access_token"],$request->status);
        if ($changeStatus["errcode"] == -1) return back()->with("status","error")->with("msg","系统错误");
        if ($changeStatus["errcode"] == 85083) return back()->with("status","error")->with("msg","搜索标记位被封禁，无法修改");
        if ($changeStatus["errcode"] == 85084) return back()->with("status","error")->with("msg","非法的 status 值，只能填 0 或者 1");
        if ($minapp->search_status != $request->status) {
            Minappslists::updateMiniListsSearchStatus($minapp->id,$request->status);
        }
        return back()->with("status","success")->with("msg","小程序搜索状态修改成功!");
    }

    public function getIllegalRecords(Request $request,$appid)
    {
        $users_id = Auth::user()->id;
        $minapp = Minappslists::getMiniListsListsByAppid($appid);
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if (empty($minapp)) return back()->with("status","error")->with("msg","您无权操作本小程序!");
        if ($minapp->users_id != $users_id && Auth::user()->authority < 3) return redirect("/admin/miniapps/miniapp_lists")->with("status","error")->with("msg","您无权操作本小程序!");

        $start_time = empty($request->start_time) ? "" : $request->start_time;
        $end_time = empty($request->end_time) ? "" : $request->end_time;
        $miniAccessToken = MiniappopenService::miniappAccessToken($minapp->appid_third,$appid);
        $records = MiniappopenService::getIllegalRecords($miniAccessToken["access_token"],$start_time,$end_time);
        $recordsLists = isset($records["records"]) ? $records["records"] : []; 
        return view("admin.miniapp.register.minapps_illegal_records",["records"=>$recordsLists]);
    }

    public function miniappBind(Request $request)
    {
        // 获取预授权码
        $preAuthcode = WechatsService::apiCreatePreauthcode();
        if (!isset($preAuthcode["pre_auth_code"])) {
            if ($preAuthcode["errcode"] == 61004) return OutputService::error("系统IP异常,请联系客服为您处理！");
        }
        $pre_auth_code = $preAuthcode["pre_auth_code"];
        $config = Config::get("wechats.open_platform.beianbao");
        $component_appid = $config["app_id"];
        // 前往授权得到授权码
        $url = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=".$component_appid."&pre_auth_code=".$pre_auth_code."&redirect_uri=https://bab.moreqifu.cn/admin/miniapps/miniapp_bind_back&auth_type=3";
        return OutputService::success("SUCCESS",["url"=>$url]);
    }

    public function miniappBindBack(Request $request)
    {
        try{
            // 授权码
            $authorization_code = $request->auth_code;
            // 使用授权码获取授权信息
            $apiQueryAuth = WechatsService::apiQueryAuth($authorization_code);
            if (isset($apiQueryAuth["errcode"])) {
                if ($apiQueryAuth["errcode"] == 61010) return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg","授权码已过期,请重新授权！");
                if ($apiQueryAuth["errcode"] == 50002) return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg","公众号/小程序已被封禁或冻结,请重新授权！");
            }

            // 获取小程序基本信息
            $openConfig = config("wechats.open_platform.beianbao");
            $basicInfo = MiniappopenService::getAccountBasicInfo($openConfig["app_id"],$apiQueryAuth["authorization_info"]["authorizer_appid"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"]);
            if (empty($basicInfo)) {
                Log::info("registerMiniappBindBack------------");
                Log::info(json_encode($basicInfo));
                Log::info("registerMiniappBindBack------------");
                return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg","授权失败请联系客服处理！");
            }
            if (isset($basicInfo["account_type"]) && $basicInfo["account_type"] != 3) return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg","此处为已有小程序授权,请勿授权公众号！");

            $config = Config::get("wechats.open_platform.beianbao");
            $component_appid = $config["app_id"];

            Miniappsauthorization::insertOpenToken($component_appid,$apiQueryAuth["authorization_info"]["authorizer_appid"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],time(),$authorization_code,1,time(),$apiQueryAuth["authorization_info"]["authorizer_access_token"],$apiQueryAuth["authorization_info"]["expires_in"],$apiQueryAuth["authorization_info"]["authorizer_refresh_token"],1);

            // 获取授权方的帐号基本信息
            $apiGetAuthorizerInfo = WechatsService::apiGetAuthorizerInfo($apiQueryAuth["authorization_info"]["authorizer_appid"]);

            $original_id = $apiGetAuthorizerInfo["authorizer_info"]["user_name"];
            // 小程序头像
            $head_img = isset($apiGetAuthorizerInfo["authorizer_info"]["head_img"]) ? $apiGetAuthorizerInfo["authorizer_info"]["head_img"] : "";
            // 小程序类型
            $service_type_info = $apiGetAuthorizerInfo["authorizer_info"]["service_type_info"]["id"];
            // 小程序认证类型
            $verify_type_info = $apiGetAuthorizerInfo["authorizer_info"]["verify_type_info"]["id"];
            // 判断小程序是否存在
            $miniapp = Minappslists::getMiniListsListsByAppid($apiQueryAuth["authorization_info"]["authorizer_appid"]);
            if (empty($miniapp)) {
                // 添加小程序数据
                $minapps_lists_id = Minappslists::gzhRegisterAuth(Auth::user()->id,$apiGetAuthorizerInfo["authorizer_info"]["nick_name"],$component_appid,$apiGetAuthorizerInfo["authorization_info"]["authorizer_appid"],$head_img,$original_id,$apiGetAuthorizerInfo["authorizer_info"]["qrcode_url"],5,4);
            } else {
                // 更新数据
                Minappslists::updateMinappsInfo($miniapp->id,["appid_third"=>$component_appid,"name"=>$apiGetAuthorizerInfo["authorizer_info"]["nick_name"],"head_img"=>$head_img,"original_id"=>$original_id,"qrcode_url"=>$apiGetAuthorizerInfo["authorizer_info"]["qrcode_url"],"disable"=>3]);
                $minapps_lists_id = $miniapp->id;
            }
            
            Minappslistsinfo::fastRegisterWeapp($minapps_lists_id,$apiGetAuthorizerInfo["authorizer_info"]["nick_name"],$apiGetAuthorizerInfo["authorizer_info"]["principal_name"],1,"","","");

            try {
                MiniappsetService::miniappAdd($apiQueryAuth["authorization_info"]["authorizer_appid"],["appid"=>$apiQueryAuth["authorization_info"]["authorizer_appid"],"users_id"=>Auth::user()->id,"name"=>$apiGetAuthorizerInfo["authorizer_info"]["nick_name"]]);
            } catch (Exception $e) {
                
            }
            
            return redirect("/admin/miniapps/miniapp_detial/".$apiQueryAuth["authorization_info"]["authorizer_appid"])->with("status","success")->with("msg","小程序授权成功,请前往上架小程序吧。");
        } catch (Exception $e) {
            $message = $e->getMessage();
            $message = json_decode(str_replace("Request access_token fail: ", "", $message));
            if (empty($message)) return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg","访问环境异常！");
            if ($message->errcode == 61003) return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg","小程序已被取消授权,请重新授权后访问！");
            if ($message->errcode == 61023) return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg","小程序授权错误,请重新授权后访问！");
            return redirect("/admin/miniapps/miniapp_register")->with("status","error")->with("msg",$message->errmsg);
        }
    }

    public function officialPush(Request $request)
    { 
        return view("admin.official.official");
    }

    public function officialPushSubmit(Request $request)
    { 
        $trmplatelist = ['','FWgwpQuO4Yg-0fJ80mtbnwRxjBgLvS6B3BXneoOvPAk','MAOEKAPwG5PFZQq1phH2saUmPj6osnVkg972NqNsXUs','RcWt_Oegfzd8BflbRFYrA3FT5S_pLIdQec70_mEIvVo','ct52Xir8YPDfODcDiuPKatsq0aD8U8qo8hrbf8XE7yM','_k-68kLY1K9s3yhU1MwUSD3bkRvyrVrBTyD1BzgINH8','jFPtZd4bPUPrJD016VKkhgNIZaQJ0OwgBKUMAALwxVg','q7AYyeTy8mo6SonXsMSA56pfkoy-LMioTgA1MCIJvVw','uGYuH4foNJ7dSxGqe4nK9bH9OWareu0C0abAwKbKXu8'];
        if(empty($request->template_id)) return back()->with("status","error")->with("msg","请选择公众号模板！");
        if(empty($request->title)) return back()->with("status","error")->with("msg","请输入通知标题！");
        if(empty($request->keyword1)) return back()->with("status","error")->with("msg","请输入关键词1！");
        if(empty($request->keyword2)) return back()->with("status","error")->with("msg","请输入关键词2！");
        if(empty($request->remark)) return back()->with("status","error")->with("msg","请输入结束语");
        if(empty($request->users_id)){
            OfficialPush::dispatch($trmplatelist[$request->template_id],$request->title,$request->keyword1,$request->keyword2,$request->keyword3,$request->keyword4,$request->keyword5,$request->remark,$request->jumpurl);
            return back()->with("status","success")->with("msg","所有会员推送成功！");
        }else{
            $users = Users::getUsersWechatOpenid($request->id);
            if(empty($users->wechat_openid)) return back()->with("status","error")->with("msg","未查询到绑定的微信");
            $paramas = [
                        'first' => $request->title,
                        'keyword1' => $request->keyword1,
                        'keyword2' => $request->keyword2,
                        'keyword3' => $request->keyword3,
                        'keyword4' => $request->keyword4,
                        'keyword5' => $request->keyword5,
                        'remark' => $request->remark,
                    ];
            WechattmplmsgService::sendSingleTempleteMsg($trmplatelist[$request->template_id],$users->wechat_openid,$request->jumpurl,"","",$paramas);
            return back()->with("status","success")->with("msg","用户推送成功！");
        }
        
    }

    public function miniRemark(Request $request)
    {
        $users = $request->user();
        $times = Minappslists::updateMinappsListsRemark($users->id,$request->appid,$request->remark);
        if($times==0) return OutputService::error("备注更新失败");
        return OutputService::success("备注更新成功");
    }

    public function miniappGetMail(Request $request)
    {
        if(empty($request->appid)) return OutputService::error("参数错误");
        $albindmail = Mail::getMailByAppid($request->appid,3,1);
        if(!empty($albindmail)) return OutputService::success("已绑定邮箱",["albindmail"=>$albindmail]);
        $albindmail = Mail::getMailByAppid($request->appid,1,0);
        if(empty($albindmail)) {
            $emptyappidmail = Mail::getMailByAppid('',1,0);
            if(empty($emptyappidmail)) return OutputService::error("暂无邮箱");
            Mail::insertAppid($emptyappidmail->id,$request->appid);
            $albindmail = Mail::getMailByAppid($request->appid,1,0);
        }
        if(empty($albindmail)) return OutputService::error("暂无邮箱");
        $num = Mail::getMailByAppidCount($request->appid);
        return OutputService::success("获取邮箱成功",["albindmail"=>$albindmail,"num"=>$num]);
    }

    public function miniappChangeMail(Request $request)
    {
        if(empty($request->appid)) return OutputService::error("参数错误");
        //判断已经切换了几个邮箱
        $num = Mail::getMailByAppidCount($request->appid);
        if($num>2) return OutputService::error("邮箱切换已达上限");
        //更新原来的不能用，获取新的邮箱
        Mail::updateStatus($request->id,$request->appid,2);
        $emptyappidmail = Mail::getMailByAppid('',1,0);
        if(empty($emptyappidmail)) return OutputService::error("暂无其他邮箱");
        Mail::insertAppid($emptyappidmail->id,$request->appid);
        $albindmail = Mail::getMailByAppid($request->appid,1,0);
        if(empty($albindmail)) return OutputService::error("暂无其他邮箱");
        return OutputService::success("邮箱切换成功",["albindmail"=>$albindmail,"num"=>$num+1]);
    }

    public function miniappBindMail(Request $request)
    {
        if(empty($request->appid)) return OutputService::error("参数错误");
        if(empty($request->id)) return OutputService::error("参数错误");
        Mail::bindMail($request->id,$request->appid);
        return OutputService::success("邮箱绑定成功");
    }

    public function wxaAuth(Request $request,$appid)
    {
        //判断有没有支付，无支付并且无支付订单前往支付
        //认证之前先获取小程序内容
        $users = Auth::user();
        if(empty($request->appid)) return back()->with("status","error")->with("msg","参数错误");
        $miniapp = Minappslists::getMiniListsListsByAppid($appid);
        if(empty($miniapp)) return back()->with("status","error")->with("msg","小程序不存在或已删除");
        $miniappOrder = Miniappsorder::miniappOrderExist($users->id,1);
        if($miniapp->pay_status == 1 && empty($miniappOrder)) return redirect("/admin/order/pay?corp_type=1")->with("status","success")->with("msg","请支付后重新发起认证");
        Minappslists::updateMiniappPayStatus($miniapp->id,$miniappOrder->order_id);
        if($miniapp->pay_status == 1) {
            Miniappsorder::miniappOrderDisable($miniappOrder->id);
        }
        // 去掉字符串里"的试用小程序"
        $miniapp->name = Str::before($miniapp->name, '的试用小程序');
        return view("admin.miniapp.wxaauth.miniapp_wxaauth",['appid'=>$appid,"miniapp"=>$miniapp]);
    }

    public function miniappOrder(Request $request)
    {
        $users = Auth::user();
        if(empty($request->appid)) return OutputService::error("参数错误");
        // 获取小程序
        $miniapp = Minappslists::getMiniListsListsByAppid($request->appid);
        if (empty($miniapp)) return OutputService::error("小程序不存在或已删除!");
        if ($miniapp->pay_status == 2) return OutputService::error("小程序已支付,无须重复操作!");
        $miniAccessToken = MiniappopenService::miniappAccessToken($miniapp->appid_third,$miniapp->appid);
        if ($miniAccessToken["status"] == "error") return OutputService::error($miniAccessToken["msg"]);
        $basicInfo = MiniappopenService::getAccountBasicInfo($miniAccessToken["access_token"]);
        $principal_type = $basicInfo["principal_type"];
        $principal_name = $basicInfo["principal_name"];
        if ($principal_type == 0) {
            $corp_type = 3;
        } else {
            if (strpos($principal_name,"（个体工商户）") !== false) {
                $corp_type = 2;
            } else {
                $corp_type = 1;
            }
        }
        $miniappOrder = Miniappsorder::miniappOrderExist($users->id,$corp_type);
        if (empty($miniappOrder)) return OutputService::error("当前暂未购买备案服务,请先购买后联系客服!",["corp_type"=>$corp_type],1002);
        // 更新小程序支付状态
        Minappslists::updateMiniappPayStatus($miniapp->id,$miniappOrder->order_id);
        Miniappsorder::miniappOrderDisable($miniappOrder->id);
        return OutputService::success("订单支付成功!");
    }
}